package com.itheima.bakery.demos.web.service.impl;

import com.itheima.bakery.demos.web.Repositories.*;
import com.itheima.bakery.demos.web.model.*;
import com.itheima.bakery.demos.web.service.CartService;
import com.itheima.bakery.demos.web.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private OrderDetailRepository orderDetailRepository;

    @Autowired
    private CartItemRepository cartItemRepository;
    @Autowired
    private InventoryRepository inventoryRepository;
    @Override
    public List<Order> findAllOrders() {
        return orderRepository.findAll();
    }

    @Override
    public Optional<Order> findOrderById(Integer id) {
        return orderRepository.findById(id);
    }

    @Override
    public Order saveOrder(Order order) {
        return orderRepository.save(order);
    }

    @Override
    public void deleteOrder(Integer id) {
        orderRepository.deleteById(id);
    }

    @Override
    @Transactional
    public void updateOrderTotal(Integer orderId) {
        BigDecimal totalAmount = orderRepository.findById(orderId)
                .map(order -> calculateTotalAmount(order.getDetails()))
                .orElse(BigDecimal.ZERO);
        orderRepository.findById(orderId).ifPresent(order -> {
            order.setTotalAmount(totalAmount);
            orderRepository.save(order);
        });
    }

    // 使用OrderDetail列表计算总金额的方法
    private BigDecimal calculateTotalAmount(List<OrderDetail> details) {
        return details.stream()
                .map(OrderDetail::getSubtotal)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
    }

    // 使用CartItem列表计算总金额的方法，方法名已更改
    private BigDecimal calculateTotalAmountFromCartItems(List<CartItem> cartItems) {
        return cartItems.stream()
                .map(CartItem::getSubtotal)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
    }


    public List<Order> getOrdersByUserId(Integer userId) {
        return orderRepository.findByUserID(userId);
    }

    @Override
    @Transactional
    public Integer createOrderAndDetails(Integer userId, List<CartItem> cartItems, HttpSession session) {
        // 创建订单对象
        Order order = new Order();
        order.setUserID(userId);
        order.setStatus(OrderStatus.Pending);

        // 使用CartItem列表计算订单总金额
        BigDecimal totalAmount = calculateTotalAmountFromCartItems(cartItems);
        order.setTotalAmount(totalAmount);

        // 保存订单
        Order savedOrder = orderRepository.save(order);

        // 为每个购物车项创建订单详情
        for (CartItem cartItem : cartItems) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrder(savedOrder);
            orderDetail.setProduct(cartItem.getProduct());
            orderDetail.setQuantity(cartItem.getQuantity());
            orderDetail.setUnitPrice(cartItem.getProduct().getPrice());
            orderDetail.setSubtotal(cartItem.getSubtotal());
            orderDetailRepository.save(orderDetail);
        }

//        // 清空数据库中的购物车项
//        cartItemRepository.deleteByUserId(userId);
//
//        // 清空会话中的购物车
//        session.removeAttribute("cart");

        return savedOrder.getOrderID();
    }



    private void clearSelectedCartItems(Integer userId, Set<Integer> productIdsToRemove, HttpSession session) {
        // 从session中获取购物车
        Cart cart = (Cart) session.getAttribute("cart");
        if (cart != null) {
            cart.getItems().removeIf(item -> productIdsToRemove.contains(item.getProductId()));
            session.setAttribute("cart", cart);
        }

        // 从数据库中删除已选择的购物车项
        cartItemRepository.deleteByUserIdAndProductIds(userId, productIdsToRemove);
    }
    @Override
    public List<OrderDetail> findOrderDetailsByOrderId(Integer orderId) {
        return orderDetailRepository.findByOrder_OrderID(orderId);
    }
}